#include "search_engine.h"

//将索引文件加载到哈希表
void Load( std::unordered_map<string,std::unordered_set<string>>& inverted_index,
           std::unordered_map<string,std::unordered_map<string,string>>& forward_index){
    Json::Reader reader;
    Json::Value value;
    std::ifstream is1,is2;
    is1.open("/home/pigff/project/search_engine/inverted_index.json");
    is2.open("/home/pigff/project/search_engine/forward_index.json");
    reader.parse(is1,value);
    vector<string> names = value.getMemberNames();
    for(auto it:names){
        vector<string> v;
        string tmp = value[it].asString();
        boost::algorithm::split(v,tmp,boost::algorithm::is_space());
        for(auto it2:v)
            inverted_index[it].insert(it2);
    }
    value.clear();
    reader.parse(is2,value);
    names.clear();
    names = value.getMemberNames();
    for(auto it:names){
        vector<string> names_names = value[it].getMemberNames();
        for(auto it2:names_names)
            forward_index[it].insert(make_pair(it2,value[it][it2].asString()));
    }
}

//对一个搜索的关键词进行分词
bool Find(std::unordered_map<string,std::unordered_set<string>> inverted_index,string keyword,std::unordered_map<string,int>& ids){
    //对给进来的关键字进行分词
    WordSegmentation wordSeg;
    vector<string> results = wordSeg(keyword);
     
    for(auto it:results){
        if(inverted_index[it].empty())
            continue;
        else{
            for(auto it2: inverted_index[it]){
                //下面的判断是因为对文件的分割结果有可能有一个是空
                if(!it2.empty())
                    ids[it2]++;
            }
        }
    }

    if(ids.empty())
        return false;

    return true;
}

//对搜索出的新闻结果按照匹配度排序
//本质上就是对一个map进行按value的排序
//因为sort只可以对顺序容器进行排序
//所以我们要先把数据存到一个vector中
//采用的方式是对sort算法采用一个仿函数Compare
class Compare{
public:
    bool operator()(const std::pair<string,int>& x, const std::pair<string,int>& y) {
        return x.second < y.second;         
    }
};
vector<std::pair<string,int> > Sort(std::unordered_map<string,int> ids){
    vector<std::pair<string,int> > ret(ids.begin(),ids.end());
    sort(ret.begin(),ret.end(),Compare());
    return ret;
}

//根据最终排序好的id取出对于的结构体数组
vector<News_Info> ReturnInfo(const vector<std::pair<string,int> >& sort_ids,
                             std::unordered_map<string,std::unordered_map<string,string>> forward_index){
    vector<News_Info> ret;
    for(auto i:sort_ids){
        News_Info news_info(forward_index[i.first]["title"],
                            forward_index[i.first]["author"],
                            forward_index[i.first]["date"]);
        ret.push_back(news_info);
    }
    return ret;
}

